/*!
 *  @author  xiaody <xiaody09@163.com>
 *  @description  UserJS for Tieba.
 */


Config.init();

var ButtonText = {
	youNigthMode : (younight === 1) ? ['夜间模式', '切换至夜间模式'] : ['白天模式', '切换至白天模式'],
	yousignSwitch : (yousign === 1) ? ['关闭签名档', '隐藏所有用户的签名档'] : ['打开签名档', '显示所有用户的签名档']
}

// Reset vars and one off functions.
younight = Config.get('nightMode') ? younight : 0;
yousign = Config.get('signSwitch') ? yousign : 0;
if(!Config.get('lastPageLink'))
	addLastPageLink = dummyFunction;
if(!Config.get('editorPlus'))
	EditorPlus.init = dummyFunction;
if(!Config.get('JKscroll'))
	HotKey.init = dummyFunction;


//(We'd better know where it is before we take any action;)
const TiebaWhere = {
	i : pathhead === 'i',
	inside : !!$(".l_container"),
	outside : !!$('#thread_list'),
	club : pathhead === 'c'
}


// OK, let's begin:
switch(true) {

	case TiebaWhere.inside :

		// Insert switch-buttons in the nav-bar.
		insertNightModeButton();
		insertSignSwitchButton();

		document.addEventListener('dblclick', badgeJump, false);

		$('#editor') && setTimeout(EditorPlus.init, 0);

		// Reset PostSuperClass's properties to make it fast.
		var postsHTML = $('.p_postlist').html();
		if(!/#.+?#|百度密语/.test(postsHTML) || !Config.get('decodePost'))
			PostSuperClass.decode = PostSuperClass.returnDOMObj;
		if(!/d_author_anonym/.test(postsHTML) || !Config.get('ipLookup'))
			PostSuperClass.addIpLink = PostSuperClass.returnDOMObj;
		if(!Config.get('floorLink'))
			PostSuperClass.addFloorLink = PostSuperClass.returnDOMObj;


		// Loop for every floor.
		var pos = $('.l_post');
		do {
			extend(pos, PostSuperClass);
			pos.addFloorLink().addIpLink().decode();
		} while(pos = pos.next());


		HotKey.init();

		break;


	case TiebaWhere.outside :

		addLastPageLink();
		insertNightModeButton();

		window.addEventListener('hashchange', function(){
			if(/!\/[mnv](?:\/p\d+)?/.test(location.hash)) {
				setTimeout(function(){
					if(addLastPageLink() === false)
						setTimeout(arguments.callee, 180);
					else if(younight !== 0)
						insertNightModeButton();
				}, 300);
			}
		}, false);

		$('#editor') && setTimeout(EditorPlus.init, 0);

		break;


	case TiebaWhere.i :
		document.addEventListener('dblclick', badgeJump, false);
		break;


	case TiebaWhere.club :
		if($('#thread_table')) {
			addLastPageLink();
		} else if(BDB_DEBUG) { // For Miyu / UUcode debug only.
			var pos = $$("table.post");
			for(var i = pos.length; i--;) {
				extend(pos[i], PostSuperClass);
				pos[i].decode(true);
			}
		}

		break;
}



// Functions.
function insertSignSwitchButton(){
	'use strict';

	if(yousign === 0 || $('#yousignSwitch'))
		return;
	if(TiebaWhere.inside) {
		if(!$('.j_quick_post'))
			return;
		var b = document.createElement('a').attr({
			id : 'yousignSwitch',
			href : '',
			title : ButtonText.yousignSwitch[1]
		});
		b.$text(ButtonText.yousignSwitch[0]).addEventListener('click', function(){switchStorage('yousign')}, true);

		var gap = $('.j_quick_post').childNodes[2].cloneNode();
		$('.j_quick_post').pushChild(gap).appendChild(b);
	}
}
function insertNightModeButton(){
	'use strict';

	if(younight === 0 || $('#youNigthMode'))
		return false;

	if(TiebaWhere.outside && $('#frs_good_nav')) {
		var a = document.createElement('span').attr('id', 'youNigthMode').attr('style', 'float:right');
		a.html('<a href>' + ButtonText.youNigthMode[1] + '</a>').addEventListener('click', function(){switchStorage('younight')}, true);
		$('#frs_good_nav').appendChild(a);
	} else if(TiebaWhere.inside) {
		if(!$('.j_quick_post'))
			return;
		var a = document.createElement('a').attr({
			id : 'youNigthMode',
			href : '',
			title : ButtonText.youNigthMode[1]
		});
		a.$text(ButtonText.youNigthMode[0]).addEventListener('click', function(){switchStorage('younight')}, true);

		var gap = $('.j_quick_post').childNodes[2].cloneNode();
		$('.j_quick_post').pushChild(gap).appendChild(a);
	}

}
function badgeJump(){
	var e = window.event, a = e.target;
	if( a.className.match('badge') && a.attr('title') ) {
		var badge_title = a.attr('title'),
			bar_location = 'http://tieba.baidu.com/f?ie=utf-8&kw=' + encodeURI(badge_title);
		window.open(bar_location);
	}
}
function switchStorage(key){
	if(typeof localStorage[key] === 'undefined')
		localStorage[key] = '1';
	localStorage[key] = -localStorage[key];
}
function addLastPageLink(){
	"use strict";

	if($('.lastPage_a'))
		return false;

	var titlePath = $$('.thread_title');
	for(var i = titlePath.length, a, b, reply, olink; i--;) {
		a = titlePath[i];
		reply = a.parentNode.attr('replay') || a.parentNode.getElementsByTagName('td')[1].innerHTML;
		if(+reply > 29){
			olink = a.getElementsByTagName('a')[0].attr('href');
			b = document.createElement('a').attr({
				'class' : 'lastPage_a',
				'href' : olink + '?pn=' + Math.ceil(++reply/30),
				'target' : '_blank'
			}).$text('-->>');
			a.appendChild(b);
		}
	}
	return true;
}

